#include<iostream>
#include<cstdlib>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string>
using namespace std;

bool GetQueryString(string& query_string)
{
    //为什么不调用cout 因为标准输入跟标准输出都被关闭了,但是标准错误没有
    //1 获得方法
    cerr << "TEST  CGI  DEBUG METHOD :" << getenv("METHOD") << endl;
    //2 获得数据
    string method = getenv("METHOD");
    
    if(method == "GET")
    {
        query_string = getenv("QUERY_STRING");

        cerr << "TEST  CGI  DEBUG QUERY_STRING :" << getenv("QUERY_STRING") << endl;

    }else if(method == "POST")
    {
        //cerr << "进入POST" << endl;
        string string_length = getenv("CONTENT_LENGTH");
        int Content_Length = atoi(string_length.c_str());
        //cerr << string_length << endl;
        char ch = '\0';
        while(Content_Length --)
        {
            ssize_t s = read(0,&ch,1);//读取数据
            query_string += ch;
        }
        cerr << "正文是: " << query_string << endl;

    }else {
        //error
        return false;
    }
    return true;
}

void CutString(string& in,string& out1,string& out2,const char& sep)
{
    auto pos = in.find(sep);
    if(pos != string::npos)
    {
        //找到了
        int t1,t2;
        t1 = t2 = 1;
        int i1 = 0,i2 = pos + 1;

        while(t1 == 1 || t2 == 1)
        {
            if(t1 == 1)
            {
                if(i1 == pos) t1 = 0;
                else out1 += in[i1++];
            }
            if(t2 == 1)
            {
                if(i2 == in.size())t2 = 0;
                else out2 += in[i2++];
            }
        }
    }
}

int main()
{
    string query_string;
    GetQueryString(query_string);

    string str1,str2;
    CutString(query_string,str1,str2,'&');

    string name1,value1;
    CutString(str1,name1,value1,'=');

    string name2,value2;
    CutString(str2,name2,value2,'=');

    int t = atoi(value1.c_str()) + atoi(value2.c_str());
    cout << value1 << " + " << value2 << '=' << t << endl; //标准输出被重定向过
    cerr << "正文是 " << t << endl;
    return 0;
}